<template>
  <div class="maintenance">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>维修管理</span>
          <div class="header-operations">
            <el-input
              v-model="searchQuery"
              placeholder="搜索技师"
              style="width: 200px; margin-right: 10px"
            />
            <el-select v-model="statusFilter" placeholder="状态筛选" style="width: 120px">
              <el-option label="全部" value="" />
              <el-option label="已取消" value="-1" />
              <el-option label="待维修" value="0" />
              <el-option label="维修中" value="1" />
              <el-option label="维修完成" value="2" />
            </el-select>
          </div>
        </div>
      </template>

      <el-table :data="filteredMaintenanceList" style="width: 100%">
        <el-table-column prop="id" label="维修ID" width="80" />
        <el-table-column prop="carInfo" label="车辆信息" min-width="150" />
        <el-table-column prop="reportDate" label="修理日期" width="120" />
        <el-table-column prop="reason" label="维修原因" min-width="150" show-overflow-tooltip />
        <el-table-column prop="technician" label="维修技师" width="100" />
        <el-table-column prop="estimatedDate" label="预计完成日期" width="120" />
        <el-table-column prop="repairRealFinishTime" label="实际完成日期" width="120">
          <template #default="scope">
            {{ scope.row.repairRealFinishTime || '未设置' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              v-if="scope.row.status === 0"
              @click="handleStartMaintenance(scope.row)"
            >
              开始维修
            </el-button>
            <el-button 
              size="small" 
              type="success" 
              v-if="scope.row.status === 1"
              @click="handleCompleteMaintenance(scope.row)"
            >
              维修完成
            </el-button>
            <el-button 
              size="small" 
              type="info" 
              @click="handleViewDetails(scope.row)"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 开始维修对话框 -->
    <el-dialog
      v-model="startMaintenanceDialogVisible"
      title="开始维修"
      width="500px"
    >
      <el-form :model="maintenanceForm" label-width="100px" :rules="maintenanceRules" ref="maintenanceFormRef">
        <el-form-item label="修理日期" prop="repairTime">
          <el-date-picker
            v-model="maintenanceForm.repairTime"
            type="date"
            placeholder="选择修理日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="预计完成日期" prop="repairExpectFinishTime">
          <el-date-picker
            v-model="maintenanceForm.repairExpectFinishTime"
            type="date"
            placeholder="选择预计完成日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="startMaintenanceDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleStartMaintenanceSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 完成维修对话框 -->
    <el-dialog
      v-model="completeDialogVisible"
      title="完成维修"
      width="500px"
    >
      <el-form :model="completeForm" label-width="100px" :rules="completeRules" ref="completeFormRef">
        <el-form-item label="维修结果" prop="result">
          <el-input
            v-model="completeForm.result"
            type="textarea"
            :rows="3"
            placeholder="请输入维修结果"
          />
        </el-form-item>
        <el-form-item label="维修费用" prop="cost">
          <el-input-number v-model="completeForm.cost" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="下次保养" prop="nextMaintenance">
          <el-date-picker
            v-model="completeForm.nextMaintenance"
            type="date"
            placeholder="选择下次保养日期"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="completeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCompleteSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 维修详情对话框 -->
    <el-dialog
      v-model="detailsDialogVisible"
      title="维修详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="维修ID">{{ currentMaintenance.id }}</el-descriptions-item>
        <el-descriptions-item label="车辆信息">{{ currentMaintenance.carInfo }}</el-descriptions-item>
        <el-descriptions-item label="报修日期">{{ currentMaintenance.reportDate }}</el-descriptions-item>
        <el-descriptions-item label="维修技师">{{ currentMaintenance.technician }}</el-descriptions-item>
        <el-descriptions-item label="维修原因" :span="2">{{ currentMaintenance.reason }}</el-descriptions-item>
        <el-descriptions-item label="维修方案" :span="2">{{ currentMaintenance.solution }}</el-descriptions-item>
        <el-descriptions-item label="维修结果" :span="2">{{ currentMaintenance.result }}</el-descriptions-item>
        <el-descriptions-item label="维修费用">{{ currentMaintenance.cost }}</el-descriptions-item>
        <el-descriptions-item label="下次保养">{{ currentMaintenance.nextMaintenance }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const maintenanceList = ref([])
const searchQuery = ref('')
const statusFilter = ref('')
const technicianOptions = ref([])  // 添加维修技师选项的定义

// 获取维修列表
const fetchMaintenanceList = async () => {
  try {
    const token = localStorage.getItem('Token')
    const url = new URL('http://localhost:8080/repair/list')
    
    // 添加分页参数
    url.searchParams.append('page', currentPage.value)
    url.searchParams.append('size', pageSize.value)
    
    // 添加搜索参数
    if (searchQuery.value) {
      url.searchParams.append('employeeName', searchQuery.value)
    }
    
    // 添加状态筛选参数
    if (statusFilter.value) {
      url.searchParams.append('status', statusFilter.value)
    }

    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Token': token
      }
    })
    
    if (response.status === 401) {
      localStorage.removeItem('Token')
      localStorage.removeItem('user')
      window.location.href = '/login'
      return
    }
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    if (result.code === 200) {
      // 处理返回的维修记录数据
      maintenanceList.value = (result.data.records || []).map(repair => ({
        id: repair.id,
        carId: repair.carId,
        carInfo: repair.carInfo,
        rentalId: repair.rentalId,
        reportDate: repair.repairTime || '未开始',
        reason: repair.repairReason,
        technician: repair.employeeName,
        estimatedDate: repair.repairExpectFinishTime || '未设置',
        repairRealFinishTime: repair.repairRealFinishTime || '未设置',
        status: repair.status,
        solution: repair.repairSolution || '',
        result: repair.repairResult || '',
        cost: repair.repairMoney || 0,
        nextMaintenance: repair.nextMaintenance || '未设置'
      }))
      total.value = result.data.total || 0
      currentPage.value = result.data.current || 1
      pageSize.value = result.data.size || 10
    } else {
      throw new Error(result.message || '获取维修列表失败')
    }
  } catch (error) {
    console.error('获取维修列表失败：', error)
    ElMessage.error('获取维修列表失败：' + error.message)
  }
}

// 监听搜索和筛选条件变化
watch([searchQuery, statusFilter], () => {
  currentPage.value = 1 // 重置页码
  fetchMaintenanceList()
})

// 处理页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchMaintenanceList()
}

// 处理每页条数改变
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchMaintenanceList()
}

// 在组件挂载时获取维修列表
onMounted(() => {
  fetchMaintenanceList()
})

// 移除本地过滤，直接使用后端分页和过滤
const filteredMaintenanceList = computed(() => {
  return maintenanceList.value
})

// 开始维修相关
const startMaintenanceDialogVisible = ref(false)
const maintenanceFormRef = ref(null)
const currentMaintenanceId = ref(null)
const maintenanceForm = reactive({
  repairTime: '',
  repairExpectFinishTime: ''
})

const maintenanceRules = {
  repairTime: [{ required: true, message: '请选择修理日期', trigger: 'change' }],
  repairExpectFinishTime: [{ required: true, message: '请选择预计完成日期', trigger: 'change' }]
}

// 完成维修相关
const completeDialogVisible = ref(false)
const completeFormRef = ref(null)
const completeForm = reactive({
  result: '',
  cost: 0,
  nextMaintenance: ''
})

const completeRules = {
  result: [{ required: true, message: '请输入维修结果', trigger: 'blur' }],
  cost: [{ required: true, message: '请输入维修费用', trigger: 'change' }],
  nextMaintenance: [{ required: true, message: '请选择下次保养日期', trigger: 'change' }]
}

// 维修详情相关
const detailsDialogVisible = ref(false)
const currentMaintenance = ref({})

// 获取维修技师列表
const fetchTechnicianList = async () => {
  try {
    const token = localStorage.getItem('Token')
    const response = await fetch('http://localhost:8080/employee/names', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Token': token
      }
    })
    
    if (response.status === 401) {
      localStorage.removeItem('Token')
      localStorage.removeItem('user')
      window.location.href = '/login'
      return
    }
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    if (result.code === 200) {
      // 将字符串数组转换为对象数组，使用索引作为id
      technicianOptions.value = (result.data || []).map((name, index) => ({
        id: index + 1,
        name: name
      }))
    } else {
      throw new Error(result.message || '获取维修技师列表失败')
    }
  } catch (error) {
    console.error('获取维修技师列表失败：', error)
    ElMessage.error('获取维修技师列表失败：' + error.message)
  }
}

// 在组件挂载时获取维修列表和技师列表
onMounted(() => {
  fetchMaintenanceList()
  fetchTechnicianList()
})

// 移除模拟数据
// const technicianOptions = ref([
//   { id: 1, name: '张工' },
//   { id: 2, name: '李工' }
// ])

const handleStartMaintenance = (row) => {
  currentMaintenanceId.value = row.id
  maintenanceForm.repairTime = new Date().toISOString().split('T')[0] // 设置默认值为今天
  maintenanceForm.repairExpectFinishTime = ''
  startMaintenanceDialogVisible.value = true
}

const handleStartMaintenanceSubmit = async () => {
  if (!maintenanceFormRef.value) return
  
  await maintenanceFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const token = localStorage.getItem('Token')
        const url = new URL(`http://localhost:8080/repair/repairing/${currentMaintenanceId.value}`)
        url.searchParams.append('repairTime', maintenanceForm.repairTime)
        url.searchParams.append('repairExpectFinishTime', maintenanceForm.repairExpectFinishTime)

        const response = await fetch(url, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
            'Token': token
          }
        })

        if (response.status === 401) {
          localStorage.removeItem('Token')
          localStorage.removeItem('user')
          window.location.href = '/login'
          return
        }

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }

        const result = await response.json()
        if (result.code === 200) {
          ElMessage.success('开始维修成功')
          startMaintenanceDialogVisible.value = false
          // 刷新页面
          window.location.reload()
        } else {
          throw new Error(result.message || '开始维修失败')
        }
      } catch (error) {
        console.error('开始维修失败：', error)
        ElMessage.error('开始维修失败：' + error.message)
      }
    }
  })
}

const handleCompleteMaintenance = (row) => {
  ElMessageBox.confirm(
    '确认完成维修？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const token = localStorage.getItem('Token')
      const response = await fetch(`http://localhost:8080/repair/repaired/${row.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Token': token
        }
      })

      if (response.status === 401) {
        localStorage.removeItem('Token')
        localStorage.removeItem('user')
        window.location.href = '/login'
        return
      }

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()
      if (result.code === 200) {
        ElMessage.success('维修完成')
        // 刷新页面
        window.location.reload()
      } else {
        throw new Error(result.message || '维修完成失败')
      }
    } catch (error) {
      console.error('维修完成失败：', error)
      ElMessage.error('维修完成失败：' + error.message)
    }
  }).catch(() => {
    // 用户点击取消按钮
    ElMessage.info('已取消操作')
  })
}

const handleViewDetails = (row) => {
  currentMaintenance.value = row
  detailsDialogVisible.value = true
}

const getStatusType = (status) => {
  const statusMap = {
    '-1': 'info',      // 已取消
    '0': 'warning',    // 待维修
    '1': 'primary',    // 维修中
    '2': 'success'     // 维修完成
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    '-1': '已取消',
    '0': '待维修',
    '1': '维修中',
    '2': '维修完成'
  }
  return statusMap[status] || '未知'
}
</script>

<style scoped>
.maintenance {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-operations {
  display: flex;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 